package com.lzb.musicplayer.activity;

import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.view.View;
import android.widget.SeekBar;

import java.io.File;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzb.basic.media.AudioPlayerImpl;
import com.lzb.basic.media.IAudioPlayer;
import com.lzb.basic.utils.FileUtil;
import com.lzb.musicplayer.BaseAc;
import com.lzb.musicplayer.Content;
import com.lzb.musicplayer.R;
import com.lzb.musicplayer.databinding.ActivityAudioEditBinding;
import com.lzb.musicplayer.dialog.RingtoneDialog;
import com.lzb.musicplayer.dialog.SaveRingtoneDialog;
import com.lzb.musicplayer.utils.RingtoneUtil;
import com.lzb.musicplayer.view.BaseAvTrackView;

import java.text.SimpleDateFormat;
import java.util.Date;

import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;

public class AudioEditActivity extends BaseAc<ActivityAudioEditBinding> implements View.OnClickListener {

    public static String audioPath;
    private AudioPlayerImpl mAudioPlayer;
    private boolean isInitTrackViewDuration = false;
    private int startProgress = 3, endProgress = 3;

    @Override
    protected int onCreate() {
        return R.layout.activity_audio_edit;
    }

    @Override
    protected void initView() {
        mDataBinding.ivAudioEditBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivStartTimeMin.setOnClickListener(this);
        mDataBinding.ivStartTimeAdd.setOnClickListener(this);
        mDataBinding.ivEndTimeMin.setOnClickListener(this);
        mDataBinding.ivEndTimeAdd.setOnClickListener(this);
        mDataBinding.tvComplete.setOnClickListener(this);
        mDataBinding.ivPlay.setOnClickListener(this);

        mAudioPlayer = new AudioPlayerImpl();
        mAudioPlayer.play(audioPath);

        mAudioPlayer.setListener(new IAudioPlayer.IListener() {
            @Override
            public void onUpdatePlayTime(int curPlayTime, int duration) {
                if (!isInitTrackViewDuration) {
                    isInitTrackViewDuration = true;
                    mDataBinding.trackView.setDuration(duration);
                }
                mDataBinding.trackView.setPlayTime(curPlayTime);
            }

            @Override
            public void onPlayChange(boolean isPlaying) {
                if (isPlaying) {
                    mDataBinding.ivPlay.setImageResource(R.drawable.stop3);
                } else {
                    mDataBinding.ivPlay.setImageResource(R.drawable.play3);
                }
            }
        });

        mDataBinding.trackView.setListener(new BaseAvTrackView.IListener() {
            @Override
            public void onStartTimeChanged(long startTime) {
                if (mAudioPlayer != null) {
                    mAudioPlayer.seekTo((int) startTime);
                    mAudioPlayer.resume();
                }
                updateView();
            }

            @Override
            public void onEndTimeChanged(long endTime) {
                if (mAudioPlayer != null) {
                    mAudioPlayer.seekTo((int) endTime);
                    mAudioPlayer.resume();
                }
                updateView();
            }

            @Override
            public void onStartEndTimeChanged(long startTime, long endTime) {
                if (mAudioPlayer != null) {
                    mAudioPlayer.seekTo((int) startTime);
                    mAudioPlayer.resume();
                }
                updateView();
            }
        });

        mDataBinding.sbStartTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                startProgress = i;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        mDataBinding.sbEndTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                endProgress = i;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivPlay) {//播放
            if (mAudioPlayer.isPlaying()) {
                mAudioPlayer.pause();
            } else {
                mAudioPlayer.resume();
            }
        } else if (id == R.id.ivStartTimeMin) {//起点时间-
            long time = mDataBinding.trackView.getStartTime() - startProgress * 100L;
            if (mDataBinding.trackView.getStartTime() < 0) time = 0;
            mDataBinding.trackView.setmStartTime(time);
        } else if (id == R.id.ivStartTimeAdd) {//起点时间+
            long time = mDataBinding.trackView.getStartTime() + startProgress * 100L;
            if (time >= mDataBinding.trackView.getEndTime()) {
                ToastUtils.showShort(getString(R.string.start_time_must_less_than_end_time));
                return;
            }
            mDataBinding.trackView.setmStartTime(time);
        } else if (id == R.id.ivEndTimeMin) {//终点时间-
            long time = mDataBinding.trackView.getEndTime() - endProgress * 100L;
            if (time <= mDataBinding.trackView.getStartTime()) {
                ToastUtils.showShort(getString(R.string.end_time_must_greater_than_start_time));
                return;
            }
            mDataBinding.trackView.setmEndTime(time);
        } else if (id == R.id.ivEndTimeAdd) {//终点时间+
            long time = mDataBinding.trackView.getEndTime() + endProgress * 100L;
            if (time >= mDataBinding.trackView.getDuration()) {
                time = mDataBinding.trackView.getDuration();
            }
            mDataBinding.trackView.setmEndTime(time);
        } else if (id == R.id.tvComplete) {
            if (audioPath == null || audioPath.isEmpty()) {
                ToastUtils.showShort("音频文件不存在");
                return;
            }

            long startTime = mDataBinding.trackView.getStartTime();
            long endTime = mDataBinding.trackView.getEndTime();

            // 验证时间范围
            if (startTime >= endTime) {
                ToastUtils.showShort("起始时间必须小于结束时间");
                return;
            }
            showSaveRingtoneDialog();
        }
        updateView();
    }

    @Override
    protected void initData() {
        mDataBinding.tvStartNum.setText(getString(R.string.time_num, startProgress * 100));
        mDataBinding.tvEndNum.setText(getString(R.string.time_num, endProgress * 100));
        updateView();
    }

    private void updateView() {
        long startTime = mDataBinding.trackView.getStartTime();
        long endTime = mDataBinding.trackView.getEndTime();
        mDataBinding.tvStartTime.setText(TimeUtils.millis2String(startTime, new SimpleDateFormat("mm:ss.SSS")));
        mDataBinding.tvDuration.setText(TimeUtils.millis2String((endTime - startTime), new SimpleDateFormat("mm:ss.SSS")));
        mDataBinding.tvEndTime.setText(TimeUtils.millis2String(endTime, new SimpleDateFormat("mm:ss.SSS")));
    }

    private void showSaveRingtoneDialog() {
        SaveRingtoneDialog dialog = new SaveRingtoneDialog(mContext);
        dialog.setText("我的铃声" + TimeUtils.getNowString(new SimpleDateFormat("yyyyMMddHHmmss")));
        dialog.setListener(new SaveRingtoneDialog.Ilistener() {
            @Override
            public void clickConfirm(String text) {
                cropAudio(text);
            }
        });
        dialog.show();
    }

    /**
     * 使用FFmpeg裁剪音频
     */
    private void cropAudio(String name) {
        long startTime = mDataBinding.trackView.getStartTime();
        long endTime = mDataBinding.trackView.getEndTime();

        String outputPath = FileUtil.generateFilePathByName(Content.myRingtone, name + "." + FileUtils.getFileExtension(audioPath));

//        String outputPath = outputDir + File.separator + "cropped_audio_" + timestamp + ".mp3";

        // 将毫秒转换为FFmpeg时间格式
        String startTimeStr = formatTimeForFFmpeg(startTime);
        String durationStr = formatTimeForFFmpeg(endTime - startTime);

        // 构建FFmpeg命令
        // -y: 覆盖输出文件
        // -i: 输入文件
        // -ss: 开始时间
        // -t: 持续时间
        // -acodec copy: 音频编码器，直接复制不重新编码（快速）
        String[] commands = {
                "ffmpeg",
                "-y",
                "-i",
                audioPath,
                "-ss",
                startTimeStr,
                "-t",
                durationStr,
                "-acodec",
                "copy",
                outputPath
        };

        // 执行FFmpeg命令
        RxFFmpegInvoke.getInstance()
                .runCommandRxJava(commands)
                .subscribe(new RxFFmpegSubscriber() {
                    @Override
                    public void onFinish() {
                        dismissDialog();
//                        ToastUtils.showShort("音频裁剪完成");
                        showRingtone(outputPath);
                    }

                    @Override
                    public void onProgress(int progress, long progressTime) {
                        // 显示进度
                        showDialog(getString(R.string.save_ing));
                    }

                    @Override
                    public void onCancel() {
                        dismissDialog();
                        FileUtils.delete(outputPath);
                        ToastUtils.showShort("音频裁剪已取消");
                    }

                    @Override
                    public void onError(String message) {
                        dismissDialog();
                        FileUtils.delete(outputPath);
                        ToastUtils.showShort("音频裁剪失败: " + message);
                    }
                });
    }

    /**
     * 将毫秒转换为FFmpeg时间格式 (HH:MM:SS.mmm)
     */
    private String formatTimeForFFmpeg(long milliseconds) {
        long totalSeconds = milliseconds / 1000;
        long hours = totalSeconds / 3600;
        long minutes = (totalSeconds % 3600) / 60;
        long seconds = totalSeconds % 60;
        long ms = milliseconds % 1000;

        if (hours > 0) {
            return String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, ms);
        } else {
            return String.format("%02d:%02d.%03d", minutes, seconds, ms);
        }
    }

    private void showRingtone(String path) {
        RingtoneDialog dialog = new RingtoneDialog(mContext);
        dialog.setText(FileUtils.getFileName(path));
        dialog.setListener(new RingtoneDialog.Ilistener() {
            @Override
            public void clickItem(int pos) {
                switch (pos) {
                    case 0: // 标准铃声
                        RingtoneUtil.setRingtone(mContext, path, RingtoneManager.TYPE_RINGTONE);
                        break;
                    case 1: // 通知声音
                        RingtoneUtil.setRingtone(mContext, path, RingtoneManager.TYPE_NOTIFICATION);
                        break;
                    case 2: // 报警声
                        RingtoneUtil.setRingtone(mContext, path, RingtoneManager.TYPE_ALARM);
                        break;
                    case 3: // 分配给联系人
                        RingtoneUtil.assignRingtoneToContact(mContext, path);
                        break;
                }
            }

            @Override
            public void clickShare() {
                shareAudio(path);
            }

            @Override
            public void clickDelete() {
                deleteAudio(path);
            }
        });
        dialog.show();
    }

    private void shareAudio(String path) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("audio/*");
        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(Intent.createChooser(shareIntent, "分享音频"));
    }

    private void deleteAudio(String path) {
        File file = new File(path);
        if (file.exists() && file.delete()) {
            ToastUtils.showShort("音频已删除");
        } else {
            ToastUtils.showShort("删除失败");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mAudioPlayer != null) {
            mAudioPlayer.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAudioPlayer != null) {
            mAudioPlayer.stop();
        }
    }

}